interface ICommonService {
    /**
     * 去重
     * @param arr 需去重的数组
     * @param matching 匹配的类型  
     */
    unique: (arr: Array<any>, matching?: string) => any

    /**
     * 转换时间
     * @param time 时间
     * @param type 转换的类型
     */
    transformTime: (time: Date, type: any) => any

    /**
     * 判断时间大小
     * @param startTime endTime 时间
     * @param message 弹出的错误信息
     */
    timeJudge: (startTime: string, endTime: string, message?: string) => any;

    /**
     * 防反跳
     * @param fn 需防反跳的函数
     * @param delay 间隔的时间
     * 在delay时间内触发则触发fn，大于delay在触发fn
     */
    debounce: (fn: any, delay: number) => any

    /**
     * 承运单附件下载
     * @param item 需要的附件的信息(id,path,name,tag)
     * @param tag 附件类型值
     * @param array 附件住数组
     * 通过name和tag值相同才下载---承运单
     * 显示图片加入path字段通过通过attachmentPath字段判断下载-----订单附件
     */
    onDownload: (item: attachmentList, tag: number, array: Array<attachmentList>) => any;

    /**
     * 附件显示
     */
    showFileItem: (attachment: any, uploader: any) => any;

    /**
     * 过滤图片格式
     */
    ownFilter: (file: File) => boolean;

    /**
     * 删除附件
     */
    onDelete: (item: any, uploaderList: any) => any;

    
    /**
     * 数组去重，
     * arr:所有属性值为基本类型的对象组成的数组，且所有对象的key相同
     */
    trimArr:(arr:any[])=>void;



}

class commonService implements ICommonService {
    baseImageUrl: string;
    constructor(private $ngBootbox: BootboxService, private routeService: routeService, private $http: ng.IHttpService,private attachmentService:attachmentService) {
        this.baseImageUrl = this.routeService.getBaseUrl() + "Attachment/";
    }
    /**
     * 去重
     */
    unique(arr: Array<any>, matching?: string): any {
        var result = [], hash = {};
        for (var i = 0, elem; (elem = arr[i]) != null; i++) {
            if (!hash[elem[matching]]) {
                result.push(elem);
                hash[elem[matching]] = true;
            }
        }
        return result;
    }

    /**
     * 转换时间
     */
    transformTime(time: Date, type: any): void {
        var t = time;
        var tf = function (i) { return (i < 10 ? '0' : '') + i };
        return type.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());
                case 'MM':
                    return tf(t.getMonth() + 1);
                case 'mm':
                    return tf(t.getMinutes());
                case 'dd':
                    return tf(t.getDate());
                case 'HH':
                    return tf(t.getHours());
                case 'ss':
                    return tf(t.getSeconds());
            }
        });
    }

    /**
     * 判断时间大小
     */
    timeJudge(startTime: string, endTime: string, message?: string): boolean {
        !message ? message = "发货时间必须小于到货时间" : message;
        var date1 = new Date(startTime);
        var date2 = new Date(endTime);
        if (date1.getTime() > date2.getTime()) {
            this.$ngBootbox.alert(message);
            return false;
        } else { return true }
    }

    /**
     * 防反跳
     */
    debounce = (action, delay) => {
        var timer = null;
        return function () {
            var self = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                action.apply(self, args)
            }, delay);
        }
    }



    /**
     * 附件下载
     */
    onDownload = (item: any, tag: any, array: Array<any>) => {
        var imgName = item._file.name;
        var filePath = item._file.fileId;
        if(!array){
            this.downAttach(filePath);
            return;
        }
        for (let i = 0; i < array.length; i++) {
            if (tag) {
                if (array[i].attachmentName == imgName && array[i].attachmentTag == tag) {
                    // window.location.href = this.baseImageUrl + array[i].attachmentId;
                    this.downAttach(array[i].attachmentId);
                    break;
                }
            } else {
                let attachmentName = array[i].attachmentName || array[i][1];
                let attachmentPath = array[i].attachmentPath || array[i][2];
                if (attachmentName == imgName && attachmentPath == filePath) {
                    let attachmentId = array[i].attachmentId || array[i][0]
                    // window.location.href = this.baseImageUrl + attachmentId;
                    this.downAttach(attachmentId);
                    break;
                }
            }
        }



    }

    downAttach(id) {
        this.attachmentService.getAttachment(id).then(res=>{
            console.log(res);
            window.location.href = this.routeService.getBaseUrl() + res.data['extData'];
        });
    }
    /**
     * 加载显示图片
     */
    showFileItem(attachment: any, uploader: any,cb?): void {
        
        // let attachmentId = attachment.attachmentId || attachment[0];
        // if(!attachmentId){return;};
        // let attachmentName = attachment.attachmentName || attachment[1];
        // let attachmentPath = attachment.attachmentPath || attachment[2];
        // if(!attachmentName){ attachmentName= '' };
        //  if(!attachmentPath){ attachmentPath= '' };
        // // let url = this.baseImageUrl + attachmentId;
        // var url;
        // this.attachmentService.getAttachment(attachmentId).then(data=>{
        //     url = this.routeService.getBaseUrl() + data.data['extData'];
            
        //     this.attachmentService.getAttachmentStr(attachmentId).then(data=>{
        //         var dataBase64 = this.dataURLtoBlob(data.data['extData'])
        //         let file = new File([dataBase64], attachmentName, { type: "image/jpg" });
        //         let dummy = new this.fileUploader.FileItem(uploader, {});
        //         file['fileId'] = attachmentPath || attachmentId;
        //         dummy._file = file;
        //         dummy.progress = 100;
        //         dummy.isUploaded = true;
        //         dummy.imgSrc = url;
        //         dummy.isSuccess = true;
        //         uploader.isLoad = false;
        //         uploader.queue.push(dummy);
        //         cb&&cb();
        //     },()=>{ 
               
        //             console.log("图片无法加载");
                
        //     });
        // });

        
    }

    dataURLtoBlob(dataurl) {
        var arr = dataurl.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        var bbb = encodeURI(arr[1])
        var bstr = window.atob(bbb), 
            n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        // return new Blob([u8arr], { type: "image/png" });
        return new Blob([u8arr], { type: mime });
    }


    /**
     * 过滤图片
     */
    ownFilter(file: File): boolean {
        let self: any = this;
        return self.queue.length < 10;
    };

    /**
     * 删除附件
     */
    onDelete = (item: any, uploaderList: any) => {
        $("input[type=file]").val("");
        var imgName = item._file.name;
        var filePath = item.file.fileId || item._file.fileId;
        for (let i = 0; i < uploaderList.length; i++) {
            let name = uploaderList[i].name || uploaderList[i].attachmentName || uploaderList[i][1];
            let path = uploaderList[i].path || uploaderList[i].attachmentPath || uploaderList[i][2];
            if (name == imgName && path == filePath) {
                uploaderList.splice(i, 1);
                break;
            }
        }
    }

    trimArr=(arr)=>{
        arr= arr.filter((item,index,array)=>{
            return array.every((_item,_index)=>{
                if(_index===index){
                    return true;
                }else{
                    return !Object.keys(_item).every(key=>{
                        return _item[key]==item[key];  // 此处
                    })
                }
            })
        })
    }


}

angular.module("commonService", []).service('commonService', ['$ngBootbox', 'routeService', '$http' ,'attachmentService', commonService]);